﻿import axios from 'axios';
import qs from 'qs';
import { Alert, Message } from 'element-ui';
import Locatization from './vue.localization';

var L = Locatization.l;

//变量
var store, global, router;

axios.defaults.withCredentials = false;

axios.interceptors.request.use((config) => {
    if (store.getters.getToken && store.getters.getToken.access_token) {
        config.headers['Authorization'] = 'Bearer ' + store.getters.getToken.access_token;
    }

    return config;
}, (error) => {
    return Promise.reject(error);
});

var FunResult = (res) => {
    //if (res.data.state === global.httpState.timeout) {
    //    //alert('登录超时！');
    //    router.push(global.BASE_URL + '/login');
    //}
    return res.data;
}

var CatchResult = (error) => {
    if (error.response && error.response.status === 403) {
        //Message.error('你没有权限!你不能执行此操作!');
        Message.error(L('AbpIdentity.DefaultErrorMessage403') + L('AbpIdentity.DefaultErrorMessage403Detail'));
    }

    if (error.response && error.response.status === 401) {
        setTimeout(() => {
            router.push(global.BASE_URL + '/Logout');
        }, 1000);
    }
    if (error.response.data && error.response.data.error && error.response.data.error.message && error.response.data.error.message !== null && error.response.data.error.message !== '') {
        //Message.error(error.response.data.error.message);
        var _msg = error.response.data.error.message;
        _msg += error.response.data.error.details;
        Message.error(_msg);
    }

    throw error.response;
}

const http = {
    init(p) {
        store = p.store;
        global = p.global;
        router = p.router;
    },
    get(url, params) {
        return axios.get(url, {
            params: params
        }).then(FunResult)
            .catch(CatchResult);
    },
    post(url, data) {
        return axios.post(url, data, {
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(FunResult)
            .catch(CatchResult);
    },
    postForm(url, data) {
        return axios.post(url, qs.stringify(data), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(FunResult)
            .catch(CatchResult);
    },
    put(url, data) {
        return axios.put(url, data, {})
            .then(FunResult)
            .catch(CatchResult);
    },
    delete(url) {
        return axios.delete(url)
            .then(FunResult)
            .catch(CatchResult);
    },
    axios: axios
}
export default http